<template>
	<view>
		<map id="map" :longitude="longitude" :latitude="latitude" scale="14" min-scale='10' max-scale='16'
			:markers="markers"  :polygons='polygons' :circles='circles' :controls='controls' @markertap='clickMarker'
			style="width: 100%; height: 100vh;">
		</map>
	</view>
	<view class="btn">
		<button @click="() => { this.show = true }">+</button>
	</view>
	<view  class="start">
		{{startGrazingNum}}
	</view>
	<view class="popup">
		<u-popup :show="show" mode="left" @close="close" @open="open">
			<view style="width: 60vw;height: 100vh;">
				<u-switch space="2" v-model="ifall" activeColor="#ff0000" inactiveColor="rgb(0, 255, 0)">
				</u-switch>
				<view>
					<text>{{ ifall ? '显示所有羊' : '仅显示出圈羊' }}	</text>
				</view>
				<u-button @tap="findAlert" type="warning" text="显示出圈羊数"></u-button>
				<u-button @tap="setNum" type="primary" text="更新羊圈中羊的数量"></u-button>
				<u-button type="success" :plain="true" text="修改围栏" @tap="updateFencing"></u-button>
				<u-button type="success" text="显示全部羊群" @tap="()=>{this.page = 0}"></u-button>
				<u-button v-for="(item) in PageCount" type="primary" :plain="  item == page ? false : true "
					@click='() => { this.page = item }'>第{{ item }}群羊</u-button>
			</view>
		</u-popup>
	</view>
	<u-popup :show="showalert" mode="center" @close="closealert" @open="openalert">
		<view class="alert">
			<view style="padding-left: 5px;padding-top:5px;margin-bottom: 10px;"><text style="font-weight: 1000;">出圈羊数</text>:<text style="color:red">{{ errnum }}</text>/{{ total }}</view>
			<scroll-view scroll-y="true" class="scroll-Y">
				<view style="width: 100%;display: flex;justify-content: space-around;">
					<text>羊羊ID</text>
					<text style="margin-right: 10px;">距离</text>
				</view>
				<ul class="modalList">
					<li class="listItem" v-for="item in errlist" :key="item._id">
						<view style="display: flex;justify-content: space-around;flex-wrap: wrap;text-align: center;line-height: 50px;">
							<text>{{ item.id }}号</text>
							<text>{{ item.dikm < 1 ? item.dikm * 100 + 'm' : item.dikm + 'km' }}</text>
						</view>
					</li>
					
				</ul>
			</scroll-view>
		</view>
		<u-button type="primary" @tap="closes">关闭警告</u-button>
	</u-popup>
</template>

<script>
import QQMapWX from '../../common/qqmap-wx-jssdk.js'
import request from '../../utils/request.js'
export default {
	data() {
		return {
			data: [],
			latitude: 43.635,
			longitude: 87.495,
			polyline: [], // 路线
			markers: [{
				id: 'myOption',
				latitude: 43.816989,
				longitude: 87.595718,
				iconPath: '/static/svg/myPosition.svg'
			}],
			circles: [
				// 	{
				// 	latitude: 43.627481,
				// 	longitude: 87.492595,
				// 	fillColor:"#0000ffAA",
				// 	color:'#ffffffAA',
				// 	radius:100
				// },
			],
			controls: [],
			polygons: [], // 多边形
			paramspolygones: [],
			qqmapsdk: null,
			a: [],
			show: false, //是否展示弹出框
			ifall: false, //是否现实所有羊
			PageCount: 0, //总页码
			page: 1, //当前页码
			vertex: [], //顶点存放位置
			jing:[],//警告顶点位置
			safe:[],//安全顶点位置
			music: null,
			showalert: false,
			errlist: [],
			total: 0,//羊群总数量
			errnum: 0,//跑出危险区外的数量
			safenum:0,//跑出警告区外的数量
			startGrazingNum:0,//开始放牧时羊群的数量
		}
	},
	onLaunch() {
		this.qqmapsdk = new QQMapWX({
			key: 'M5JBZ-XEZCJ-6SPFB-DH4E5-QFCS7-FCBTQ'
		});
		uni.onLocationChange(function (res) {
			console.log('纬度：' + res.latitude);
			console.log('经度：' + res.longitude);
		});
		uni.onLocationChangeError((e) => {
			// console.log(e);
		})
	},
	onLoad() {
		this.qqmapsdk = new QQMapWX({
			key: 'M5JBZ-XEZCJ-6SPFB-DH4E5-QFCS7-FCBTQ'
		});
		request("/cyp/one").then((res)=>{
			this.jing = res.data.polygons
		})
		//安全区
		request("/cyp/two").then((res)=>{
			this.safe = res.data.polygonstwo
		})
		//危险区
		request('/cyp').then((res) => {
			this.vertex = res.data.fence
		}).finally(() => {
			this.polygons = [{
				points: [...this.vertex],
				fillColor: "#ff985d66", // 填充颜色
				strokeColor: "#ff985d66", // 描边颜色
				strokeWidth: 2, // 描边宽度
				zIndex: 3 //层级
			},{
				points: [...this.jing],
				fillColor: "#ff00ff", // 填充颜色
				strokeColor: "#ff00ff", // 描边颜色
				strokeWidth: 2, // 描边宽度
				zIndex: 4 //层级
			},
			{
				points: [...this.safe],
				fillColor: "#00ff00", // 填充颜色
				strokeColor: "#55ff00", // 描边颜色
				strokeWidth: 2, // 描边宽度
				zIndex: 4 //层级
			},]
			this.getlist()
			//危险区触发警告
			this.Inquire(this.vertex)
			this.jinggao(this.jing)
			this.getNum()
		})

	},
	onUnload: function () {
		this.closealert()
		this.showalert = false
	},
	methods: {
		clickMarker(){
			console.log(1
			);
		},
		async setNum(){
			console.log('setNum');
			await request('/zq/InquireSecurePage')
			this.getNum()
		},
		getNum(){
			request('/zq/setNum').then(res=>{
				this.startGrazingNum = res.data.num
			})
		},
		//打开警告
		open() {
			console.log('open');
		},
		//关闭警告
		close() {
			this.show = false
			this.getlist()
		},
		//关闭警告页面和报警
		findAlert() {
			this.show = false;
			this.showalert = true;
		},
		// 获取某个羊群的羊，以及所有的羊
		getlist() {
			request('/zq/InquirePage?page=' + this.page, { data: this.vertex }, 'POST')
				.then(res => {
					if (this.ifall) {
						this.markers = [...res.data.list, ...res.data.errorList];
					} else {
						this.markers = [...res.data.errorList];
					}
					this.PageCount = res.data.PageCount;
				})
				.catch(error => {
					console.error(error);
				});
		},
		// 获取跑出危险区外的羊
		Inquire(array) {
		
			request('/gjs/Inquire', { markers: array }, 'POST')
				.then(({ data }) => {
					let { list, errornum, total } = data;
					this.errnum = errornum;
					this.total = total;
					this.markers = list;
					list.forEach(item => {
						this.getPathing(item);
					});
					if (list.length !== 0) {
						this.ScanAudio();
						this.openalert();
					}
				})
				.catch(error => {
					console.error(error);
				});

		},
		//获取跑出警告区外的羊
		jinggao(array) {
			request('/gjs/warn', { markers: array },
			 'POST')
				.then(({ data }) => {
					let { list, errornum, total } = data;
					this.safenum = errornum - this.errnum
				})
				.catch(error => {
					console.error(error);
				});
		},
		//语音报警和震动报警
		ScanAudio() {
			let music = uni.createInnerAudioContext();
			music.loop = true
			music.src ='https://img.tukuppt.com/newpreview_music/09/00/13/5c8902563671136874.mp3';
			music.play()
			this.music = music
			uni.vibrateLong()
			this.thime = setInterval(() => {
				uni.vibrateLong()
			}, 1000)
		},
		closealert() {
			this.showalert = false
			setTimeout(()=>{
				this.music.stop()
			},300)
			this.thime ?clearInterval(this.thime):''
		},
		closes() {
			this.showalert = false
			setTimeout(()=>{
				this.music.stop()
			},300)
			this.thime ?clearInterval(this.thime):''
		},
		openalert() {
			this.showalert = true
		},
		seek(id) {
			this.closealert()
			this.showalert = false
			uni.navigateTo({
				url: '/pages/driverHome/driverHome?id=' + id
			})
		},
		getPathing(obj) {
			// 暂存this---direction方法里面会用到
			let that = this
			// 获取当前地理位置
			this.qqmapsdk.direction({
				mode: 'driving',
				from: {
					latitude: 43.61122246320031,
					longitude: 87.50078201293945
				},
				to: {
					latitude: obj.latitude,
					longitude: obj.longitude
				},
				// 执行成功的回调
				success: function (res, data) {
					// //坐标解压（返回的点串坐标，通过前向差分进行压缩）
					let dikm = Number(res.result.routes[0].distance) / 1000
					that.errlist.push({
						id: obj.id,
						_id: obj._id,
						dikm: dikm.toFixed(2)
					})
				}
			})
		},
		updateFencing() {
			this.close()
			uni.navigateTo({
				url: '/pages/content/content'
			})
		}
	},
}
</script>

<style lang="scss">
	.modalList{
		margin-top: 10px;
		.listItem:nth-child(2n-1){
			background-color: whitesmoke;
		}
	}
.btn {
	position: fixed;
	top: 0;
	left: 0;
}

.alert {
	width: 600rpx;
	height: 500rpx;
}

.scroll-Y {
	width: 600rpx;
	height: 460rpx;
}

.scroll-view-item {
	height: 200rpx;
	font-size: 36rpx;

	.info {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: space-between;
		line-height: 120rpx;

		image {
			width: 130rpx;
			height: 130rpx;
			border-radius: 50%;
		}
	}
}
.start{
	position: fixed;
	top: 0;
	right: 0;
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	background: aquamarine;
	text-align: center;
	line-height: 100rpx;
}
</style>